package com.hs;

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author: hs
 * @Description:
 * @Date: Create in 09:53 2019/4/30
 */
public class ThreadPoolExecutorTest  implements RejectedExecutionHandler {

    final static  AtomicInteger atomicInteger = new AtomicInteger();

    public static void main(String[] args) {
        //初始时，新进的任务会直接开新线程去处理。当线程数量=corePoolSize时，再新增任务放入 blockingqueue中。
        //当BlockingQueue满了时，多出了任务会直接再开新线程处理，直到总线程数达到maximunPoolSize时。
        //总线程数达到maximunPoolSize，且BlockingQueue也满了时，就会调拒绝执行处理器RejectedExecutionHandler
        ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 50, 10, TimeUnit.MINUTES,
                new ArrayBlockingQueue<>(10),new ThreadPoolExecutorTest());
        try {
            for (int i = 0; i <50; i++) {
                executor.execute(new myRunable());
                //executorService.submit();
                System.out.println(executor.getQueue().size());
                System.out.println(executor.getPoolSize());
                System.out.println(executor.getTaskCount());
                System.out.println(executor.getActiveCount());
                System.out.println(executor.getLargestPoolSize());
                Thread.sleep(50);
            }
            System.out.println("添加完");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            executor.shutdown();
        }
    }


    @Override
    public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
        System.out.println("任务溢出。。等会再放进去。。这里就有问题 溢出处理 与核心数、最大数，队列数的问题了");
        //要想达到最大的线程数量，就必须撑爆 阻塞队列 会执行设定的策略 。 考虑根据 限速 从新访问去？
        //改线程是主线程，不能随便sleep的节奏
        try {
            System.out.println("溢出。。。");
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        executor.execute(r);
    }

    public static class myRunable implements Runnable {
        @Override
        public void run() {
            try {
                System.out.println("run..."+atomicInteger.incrementAndGet());
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
